package com.amt.util;

import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

import java.security.MessageDigest;
import java.util.UUID;

/**
 * @Title: MD5Util.java 
 * @Package com.meatball.util
 * @Description: TODO(带盐加密MD5工具类) 
 * @author 江伟  
 * @date 2019年12月14日 下午4:26:44 
 * Copyright (c) ©1994-2018 Scjydz.com All Rights Reserved.
 */
public class MD5Util {
	// 加盐参数
    public final static String hashAlgorithmName = "MD5";

    // 循环次数
    public final static int hashIterations = 1024;
  

    /**
     * @Description: shiro密码加密工具类
     * @param credentials 密码
     * @param saltSource 密码盐
     * @return String    返回类型
     */
    public static String md5(String credentials, String saltSource) {
        ByteSource salt = new Md5Hash(saltSource);
        return new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations).toString();
    }
    
    private static String byteArrayToHexString(byte b[]) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++)
            resultSb.append(byteToHexString(b[i]));

        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n += 256;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }
    private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

    /**
     * @Description: md5 加密签名
     * @param origin
     * @param charsetname
     * @return
     */
    public static String MD5Encode(String origin, String charsetname) {
        String resultString = null;
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname == null || "".equals(charsetname))
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes()));
            else
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes(charsetname)));
        } catch (Exception exception) {
        }
        return resultString;
    }

    /**
     * @description: 获取12位随机数字
     * @return 随机数
     */
    public static String getRandomNumber() {
        Integer orderId = UUID.randomUUID().toString().hashCode();
        orderId = orderId < 0 ? - orderId : orderId;
        return 1+String.format("%011d", orderId);
    }

    public static void main(String[] args) {
        String s = md5("123456", "p0bfcism9k46gpm7yof7v9sp1j4uy1kklnk8sk2nyytho");
        System.out.println(s);
    }
}
